import 'package:flutter/material.dart';
import 'package:flutter_billi/http/core/hi_error.dart';
import 'package:flutter_billi/http/core/hi_state.dart';
import 'package:flutter_billi/http/dao/home_dao.dart';
import 'package:flutter_billi/model/home_mo.dart';
import 'package:flutter_billi/navgator/bottom_navigator.dart';
import 'package:flutter_billi/navgator/hi_navigator.dart';
import 'package:flutter_billi/page/detail_page.dart';
import 'package:flutter_billi/page/home_tab_page.dart';
import 'package:flutter_billi/page/profile_page.dart';

import 'package:flutter_billi/util/toast.dart';
import 'package:flutter_billi/util/view_util.dart';
import 'package:flutter_billi/widget/HiTab.dart';
import 'package:flutter_billi/widget/NavigationBar.dart';
import 'package:flutter_billi/widget/load_container.dart';

// flutter 监听 生命 周期的变化  使用 WidgetsBindingObserver

class HomePage extends StatefulWidget {
  final ValueChanged<int> onJumpTo;

  const HomePage({Key key, this.onJumpTo}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends HiState<HomePage>
    with AutomaticKeepAliveClientMixin, TickerProviderStateMixin, WidgetsBindingObserver {
  TabController _controller;
  List<CategoryMo> categoryList = [];
  List<BannerMo> bannerList = [];

  bool isLoading = true;
  var Listener;

  Widget _currentPage;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _controller = TabController(length: categoryList.length, vsync: this);
    HiNavigator.getInstance().addListener(this.Listener = (current, pre) {
      this._currentPage = current.page;
      print('home:current:${current.page}');
      print("home:pre:${pre?.page}");

      if (widget == current.page || current is BottomNavigator) {
        print("打开了首页 onResume");
      } else if (widget == pre?.page || pre?.page is BottomNavigator) {
        print("首页 后台运行 onPause");
      }

      // 当页面 返回首页 恢复首页 的状态栏样式
      if (pre?.page is VideoDetailPage && !(current.page is ProfilePage)) {
        var statusStyle = StatusStyle.DARK_CONTENT;
        changeStatusBar(color: Colors.white, statusStyle: statusStyle);
      }
    });
    loadData();
  }

  @override
  void dispose() {
    _controller.dispose();
    WidgetsBinding.instance.removeObserver(this);
    HiNavigator.getInstance().removeListener(this.Listener);
    super.dispose();
  }

  //监听生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // TODO: implement didChangeAppLifecycleState
    super.didChangeAppLifecycleState(state);
    print(":didChangeAppState: ${state}");

    switch (state) {
      case AppLifecycleState.inactive: //处于这种状态的应用程序  应该假设他们在任何时候暂停
        break;
      case AppLifecycleState.resumed: // 从后台切换到前台， 界面可见
        if (!(_currentPage is VideoDetailPage)) {
          changeStatusBar(color: Colors.white, statusStyle: StatusStyle.DARK_CONTENT);
        }
        break;
      case AppLifecycleState.paused: // 从后台进入前台 ， 界面不可见
      case AppLifecycleState.detached: // 终结态， app 结束调用
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: LoadContainer(
      cover: true,
      isLoading: isLoading,
      child: Column(
        children: [
          NavigationBar(
            height: 50,
            child: _appBar(),
            color: Colors.white,
            statusStyle: StatusStyle.DARK_CONTENT,
          ),
          Container(
              child: _tabBar(),
              // color: Colors.white,
              decoration: bottomBoxShadow()
              // padding: EdgeInsets.only(top: 30),
              ),
          Flexible(
              child: TabBarView(
            controller: _controller,
            children: categoryList.map((tab) {
              return HomeTabPage(
                categoryName: tab.name,
                bannerList: tab.name == "推荐" ? bannerList : null,
              );
            }).toList(),
          )),
        ],
      ),
    ));
  }

  @override
  bool get wantKeepAlive => true;

  _tabBar() {
    return HiTab(
      categoryList.map<Tab>((tab) {
        return Tab(
          text: tab.name,
        );
      }).toList(),
      controller: _controller,
      fontSize: 16,
      borderWidth: 3,
      unselectedLabelColor: Colors.black54,
      insets: 13,
    );
  }

  void loadData() async {
    try {
      HomeMo result = await HomeDao.get('推荐');
      print('loadata${result}');
      if (result.categoryList != null) {
        _controller = TabController(length: result.categoryList.length, vsync: this);
      }
      setState(() {
        categoryList = result.categoryList;
        bannerList = result.bannerList;
        isLoading = false;
      });
    } on NeedAuth catch (err) {
      print(err);
      setState(() {
        isLoading = false;
      });
      showWarnToast(err.message);
    } on HiNetError catch (err) {
      showWarnToast(err.message);
      setState(() {
        isLoading = false;
      });
    }
  }

  _appBar() {
    return Padding(
      padding: EdgeInsets.only(left: 15, right: 15),
      child: Row(
        children: [
          InkWell(
            onTap: () {
              if (widget.onJumpTo != null) {
                widget.onJumpTo(3);
              }
            },
            child: ClipRRect(
              borderRadius: BorderRadius.circular(23),
              child: Image(
                height: 46,
                width: 46,
                image: AssetImage('images/avatar.png'),
              ),
            ),
          ),
          Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 15, right: 15),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(16),
                child: Container(
                  padding: EdgeInsets.only(left: 10),
                  height: 32,
                  alignment: Alignment.centerLeft,
                  child: Icon(
                    Icons.search,
                    color: Colors.grey,
                  ),
                  decoration: BoxDecoration(color: Colors.grey[100]),
                ),
              ),
            ),
          ),
          Icon(
            Icons.explore_outlined,
            color: Colors.grey,
          ),
          Padding(
            padding: EdgeInsets.only(left: 12),
            child: Icon(
              Icons.mail_outline,
              color: Colors.grey,
            ),
          )
        ],
      ),
    );
  }
}
